package a02_链表;

/**
 * <p>
 * a05_删除链表的倒数第N个节点
 * </p>
 *
 * @author flyduck
 * @since 2024-06-19
 */
public class a06_删除链表的倒数第N个节点复习4 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode listNode = removeNthFromEnd(head, 2);
        ListNode temp = listNode;
        while (temp != null) {
            System.out.println(temp.val);
            temp = temp.next;
        }
    }

    //a->b->c->d->e->f->g->h
    //slow
    //            fast
    public static ListNode removeNthFromEnd(ListNode head, int n) {//n=3
        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;

        ListNode slowNode = dummyNode;
        ListNode fastNode = dummyNode;
        while (n + 1 > 0) {
            fastNode = fastNode.next;
            n--;
        }


        while (fastNode != null){
            slowNode = slowNode.next;
            fastNode = fastNode.next;
        }

        slowNode.next = slowNode.next.next;
        return dummyNode.next;
    }
}
